package com.san.metadata.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.pool.DruidPooledPreparedStatement;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.san.base.dao.BaseManager;
import com.san.base.domain.CodeDO;
import com.san.base.service.CodeService;
import com.san.common.datasource.JdbcManager;
import com.san.common.utils.AESUtils;
import com.san.common.utils.Constant;
import com.san.common.utils.DateUtils;
import com.san.common.utils.MD5Utils;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.StringUtils;
import com.san.earlyWarning.domain.EarlyWarningDO;
import com.san.metadata.domain.BaseLegalPersonDO;
import com.san.metadata.domain.BaseNaturalPersonDO;
import com.san.metadata.domain.BusinessDataDO;
import com.san.metadata.domain.ColumnDTO;
import com.san.metadata.domain.DataSourceDO;
import com.san.metadata.domain.ManageColumnsDO;
import com.san.metadata.domain.ManageTableDO;
import com.san.metadata.domain.OperationJobDO;
import com.san.metadata.domain.TechnicalColumnsDO;
import com.san.metadata.domain.TechnicalTableDO;
import com.san.metadata.service.BaseLegalPersonService;
import com.san.metadata.service.BaseNaturalPersonService;
import com.san.metadata.service.DataSourceService;
import com.san.metadata.service.ManageMetadataService;
import com.san.metadata.service.OperationExtLogService;
import com.san.metadata.service.OperationJobService;
import com.san.metadata.service.OperationLogService;
import com.san.metadata.service.TechnicalMetadataService;
import com.san.metadata.vo.BaseLegalPersonVO;
import com.san.metadata.vo.BaseNaturalPersonVO;
import com.san.metadata.vo.OperationExtLogVO;
import com.san.metadata.vo.OperationLogVO;
import com.san.warnings.domain.WarningsBusiDO;
import com.san.warnings.domain.WarningsModelDO;
import com.san.warnings.service.WarningsService;

/**
 * 操作元数据jdbc访问层
 * 
 * @author xiangyz
 *
 */
@Service
public class OperationMetadataManager extends BaseManager {

	private static final Logger logger = LoggerFactory.getLogger(OperationMetadataManager.class);

	@Autowired
	TechnicalMetadataService technicalMetadataService;

	@Autowired
	ManageMetadataService manageMetadataService;

	@Autowired
	DataSourceService dataSourceService;

	@Autowired
	OperationJobService operationJobService;

	@Autowired
	OperationLogService operationLogService;

	@Autowired
	OperationExtLogService operationExtLogService;

	@Autowired
	CodeService codeService;

	@Autowired
	BaseLegalPersonService baseLegalPersonService;

	@Autowired
	BaseNaturalPersonService baseNaturalPersonService;

	@Autowired
	BasePersonCache basePersonCache;

	@Autowired
	WarningsService warningsService;

	/**
	 * 数据同步至技术元数据
	 * 
	 * @param batchNo
	 * @param jobId
	 * @param technicalTableDO
	 * @return
	 */
	public Long exchangeToTechnicalMetadata(Long batchNo, Long jobId, TechnicalTableDO technicalTableDO) {
		// 执行开始时间
		Date beginTime = new Date();
		DruidPooledConnection conn = null;
		DruidPooledPreparedStatement ps = null;
		// 同步结果集
		ResultSet rs = null;

		// 同步数量
		long total = 0;
		JdbcManager jdbcManager = new JdbcManager();
		try {
			List<TechnicalColumnsDO> listColumns = technicalMetadataService
					.allTechnicalColumns(technicalTableDO.getTableId());
			if (null == listColumns || listColumns.size() == 0) {
				return 0l;
			}

			DataSourceDO dataSourceDO = (DataSourceDO) dataSourceService.getById(technicalTableDO.getSourceId());

			// 源表查询字段
			StringBuffer selectColumns = new StringBuffer();

			// 目标表写入字段
			StringBuffer insertColumns = new StringBuffer();
			// 目标表写入动态匹配值(?)
			StringBuffer insertParams = new StringBuffer();
			String businessTime = null;
			// 来源表字段
			List<String> columns = new ArrayList<String>();
			// 迭代字段信息，构建查询字段，写入字段
			for (TechnicalColumnsDO technicalColumnsDO : listColumns) {
				selectColumns.append(technicalColumnsDO.getColumnName()).append(",");

				if (technicalColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_INPUT_DATE + ",") >= 0) {
					businessTime = technicalColumnsDO.getColumnName();
				}

				insertColumns.append(technicalColumnsDO.getColumnName()).append(",");
				insertParams.append("?,");

				columns.add(technicalColumnsDO.getColumnName());
			}

			StringBuffer fromSQL = new StringBuffer("select ");
			fromSQL.append(selectColumns.substring(0, selectColumns.length() - 1));
			fromSQL.append(" from ").append(technicalTableDO.getSourceTableName());
			List<Object> queryParams = new ArrayList<Object>();
			if (Constant.CHANGE_TYPE_INCREMENT == technicalTableDO.getChangeType()) {
				if (null == businessTime) {
					this.saveOperationLog(batchNo, jobId, technicalTableDO.getTableId(), Constant.STATUS_DELETE, 0,
							"增量同步未配置入库时间字段，同步终止", beginTime, new Date());
					return 0l;
				}
				fromSQL.append(" where ");
				if (Constant.SOURCE_TYPE_ORACLE == dataSourceDO.getSourceType()) {
					fromSQL.append(" to_char(").append(businessTime).append(",'yyyymmdd') = ?");
				} else if (Constant.SOURCE_TYPE_MYSQL == dataSourceDO.getSourceType()) {
					fromSQL.append(" date_format(").append(businessTime).append(",'%Y%m%d') = ?");
				} else {
					this.saveOperationLog(batchNo, jobId, technicalTableDO.getTableId(), Constant.STATUS_DELETE, 0,
							"未知数据库类型，同步终止", beginTime, new Date());

					return 0l;
				}
				queryParams.add(DateUtils.getYesterday("yyyyMMdd"));
			}
			conn = this.getDBConnection(dataSourceDO.getSourceCode());
			// 查询需要交换的数据
			Map<String, Object> result = jdbcManager.executeQueryByType(conn, fromSQL.toString(),
					queryParams.toArray());
			rs = (ResultSet) result.get("rs");
			ps = (DruidPooledPreparedStatement) result.get("ps");

			DataSourceDO targetDataSourceDO = (DataSourceDO) dataSourceService
					.getById(technicalTableDO.getTargetSourceId());

			if (Constant.CHANGE_TYPE_ALL == technicalTableDO.getChangeType()) {
				String bakTableName = bakTable(technicalTableDO.getTargetTableName(),
						targetDataSourceDO.getSourceCode());

				this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, technicalTableDO.getTableId(),
						technicalTableDO.getTargetTableName() + ",全量同步表备份为：" + bakTableName);
			}

			total = insertData(targetDataSourceDO.getSourceCode(), technicalTableDO.getTargetTableName(), columns,
					insertColumns.toString(), insertParams.toString(), rs);

			this.saveOperationLog(batchNo, jobId, technicalTableDO.getTableId(), Constant.STATUS_NORMAL, total, "成功",
					beginTime, new Date());
		} catch (Exception e) {

			StringBuffer errorMsg = new StringBuffer(e.toString());
			errorMsg.append("\n");
			StackTraceElement[] ses = e.getStackTrace();
			errorMsg.append(ses[ses.length - 1]);

			try {
				this.saveOperationLog(batchNo, jobId, technicalTableDO.getTableId(), Constant.STATUS_DELETE, total,
						errorMsg.toString(), beginTime, new Date());
			} catch (Exception e1) {
				logger.error("日志写入失败", e);
			}
		} finally {

			// 关闭查询结果集
			try {
				if (null != ps) {
					ps.close();
				}
				if (null != conn) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		return total;
	}

	/**
	 * 备份表，更换表名再建表
	 * 
	 * @param targetTableName
	 * @param dataSourceCode
	 * @return 备份表名称
	 */
	public String bakTable(String targetTableName, String dataSourceCode) throws Exception {
		JdbcManager jdbcManager = new JdbcManager();
		String bakTableName = targetTableName + DateUtils.getYesterday("MMdd");
		if (bakTableName.length() > 30) {
			bakTableName = "BAK_" + DateUtils.getNow();
		}
		// 更换表名
		jdbcManager.executeSQL(this.getDBConnection(dataSourceCode),
				"alter table " + targetTableName + " RENAME TO " + bakTableName, new Object[] {});

		// 创建表
		jdbcManager.executeSQL(this.getDBConnection(dataSourceCode),
				"create table " + targetTableName + " as select * from " + bakTableName + " where 1 = 2",
				new Object[] {});

		return bakTableName;
	}

	/**
	 * 写入数据
	 * 
	 * @param dataSourceCode   写入数据源编码
	 * @param technicalTableDO 技术元数据表DO
	 * @param listColumns      技术元数据表列集合
	 * @param insertColumns    需要插入的表字段
	 * @param insertParams     需要插入的动态匹配参数
	 * @param rs
	 * @return
	 * @throws Exception
	 */
	public long insertData(String dataSourceCode, String targetTableName, List<String> listColumns,
			String insertColumns, String insertParams, ResultSet rs) throws Exception {

		StringBuffer insertSQL = new StringBuffer();
		insertSQL.append("insert into ").append(targetTableName);
		insertSQL.append(" (").append(insertColumns.substring(0, insertColumns.length() - 1)).append(")");
		insertSQL.append(" values (").append(insertParams.substring(0, insertParams.length() - 1)).append(")");

		List<Object[]> listParams = new ArrayList<Object[]>();
		List<Object> params = null;
		JdbcManager jdbcManager = new JdbcManager();
		long count = 0;
		while (rs.next()) {
			params = new ArrayList<Object>();
			for (String columnName : listColumns) {
				if (StringUtils.isEmpty(columnName)) {
					params.add(null);
				} else {
					params.add(rs.getObject(columnName));
				}

			}

			listParams.add(params.toArray());

			if (listParams.size() >= COMMIT_SIZE) {
				jdbcManager.batchExecuteSQL(this.getDBConnection(dataSourceCode), insertSQL.toString(), listParams);

				listParams = new ArrayList<Object[]>();
			}
			count++;
		}

		if (listParams.size() > 0) {
			jdbcManager.batchExecuteSQL(this.getDBConnection(dataSourceCode), insertSQL.toString(), listParams);

			listParams = null;
		}

		return count;
	}

	/**
	 * 指定表-表数据同步
	 * 
	 * @param batchNo
	 * @param jobId
	 * @param technicalTableDO
	 * @return
	 */
	public Long dataSync(Long batchNo, Long jobId) {
		// 执行开始时间
		Date beginTime = new Date();

		JdbcManager jdbcManager = new JdbcManager();
		DruidPooledConnection conn = null;
		DruidPooledPreparedStatement ps = null;
		// 同步结果集
		ResultSet rs = null;

		// 同步数量
		long total = 0;
		try {

			OperationJobDO operationJobDO = operationJobService.getById(jobId);

			// 来源表所属数据源ID
			Long sourceDataSourceId = 0l;
			// 来源表表名
			String sourceTableName = null;
			if (Constant.META_TYPE_TECHNICAL == operationJobDO.getSourceMetaType()) {
				TechnicalTableDO technicalTableDO = technicalMetadataService.getById(operationJobDO.getSourceTable());
				sourceDataSourceId = technicalTableDO.getTargetSourceId();
				sourceTableName = technicalTableDO.getTargetTableName();
			} else if (Constant.META_TYPE_MANAGE == operationJobDO.getSourceMetaType()) {
				ManageTableDO manageTableDO = manageMetadataService.getById(operationJobDO.getSourceTable());
				sourceDataSourceId = manageTableDO.getTargetSourceId();
				sourceTableName = manageTableDO.getTargetTableName();
			}

			DataSourceDO dataSourceDO = (DataSourceDO) dataSourceService.getById(sourceDataSourceId);

			// 源表查询字段
			StringBuffer selectColumns = new StringBuffer();

			// 目标表写入字段
			StringBuffer insertColumns = new StringBuffer();
			// 目标表写入动态匹配值(?)
			StringBuffer insertParams = new StringBuffer();

			// 来源表字段
			List<String> columns = new ArrayList<String>();

			if (null != operationJobDO.getColumnRelation() && !"".equals(operationJobDO.getColumnRelation())) {
				JSONArray listColumns = JSONArray.parseArray(operationJobDO.getColumnRelation());
				for (int i = 0; i < listColumns.size(); i++) {
					JSONObject obj = (JSONObject) listColumns.get(i);
					selectColumns.append(this.conversionColumn(obj.getString("sc"))).append(",");
					insertColumns.append(obj.getString("tc")).append(",");
					// TODO 增量，全量
					insertParams.append("?,");

					columns.add(obj.getString("sc"));
				}
			}

			StringBuffer fromSQL = new StringBuffer("select ");
			fromSQL.append(selectColumns.substring(0, selectColumns.length() - 1));
			fromSQL.append(" from ").append(sourceTableName);
			List<Object> queryParams = new ArrayList<Object>();

			conn = this.getDBConnection(dataSourceDO.getSourceCode());
			// 查询需要交换的数据
			Map<String, Object> result = jdbcManager.executeQueryByType(conn, fromSQL.toString(),
					queryParams.toArray());
			rs = (ResultSet) result.get("rs");
			ps = (DruidPooledPreparedStatement) result.get("ps");

			// 目标表所属数据源ID
			Long targetDataSourceId = 0l;
			// 目标表表名
			Long targetTableId = null;
			// 目标表表名
			String targetTableName = null;
			if (Constant.META_TYPE_TECHNICAL == operationJobDO.getTargetMetaType()) {
				TechnicalTableDO technicalTableDO = technicalMetadataService.getById(operationJobDO.getTargetTable());
				targetDataSourceId = technicalTableDO.getTargetSourceId();
				targetTableId = technicalTableDO.getTableId();
				targetTableName = technicalTableDO.getTargetTableName();
			} else if (Constant.META_TYPE_MANAGE == operationJobDO.getTargetMetaType()) {
				ManageTableDO manageTableDO = manageMetadataService.getById(operationJobDO.getTargetTable());
				targetDataSourceId = manageTableDO.getTargetSourceId();
				targetTableId = manageTableDO.getTableId();
				targetTableName = manageTableDO.getTargetTableName();
			}

			DataSourceDO targetDataSourceDO = (DataSourceDO) dataSourceService.getById(targetDataSourceId);

			total = insertData(targetDataSourceDO.getSourceCode(), targetTableName, columns, insertColumns.toString(),
					insertParams.toString(), rs);

			this.saveOperationLog(batchNo, jobId, targetTableId, Constant.STATUS_NORMAL, total, "成功", beginTime,
					new Date());
		} catch (Exception e) {

			StringBuffer errorMsg = new StringBuffer(e.toString());
			errorMsg.append("\n");
			StackTraceElement[] ses = e.getStackTrace();
			errorMsg.append(ses[ses.length - 1]);

			try {
				this.saveOperationLog(batchNo, jobId, null, Constant.STATUS_DELETE, total, errorMsg.toString(),
						beginTime, new Date());
			} catch (Exception e1) {
				logger.error("日志写入失败", e);
			}
		} finally {

			try {
				if (null != ps) {
					// 关闭预处理
					ps.close();
				}
				if (null != conn) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		return total;
	}

	public String conversionColumn(String columnName) {
		return null == columnName || "".equals(columnName) ? "null" : columnName;
	}

	/**
	 * 数据同步至管理元数据，并进行清洗比对处理
	 * 
	 * @param batchNo
	 * @param jobId
	 * @param manageTableDO
	 * @return
	 */
	public Long processManageMetadata(Long batchNo, Long jobId, ManageTableDO manageTableDO) {

		this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTableId(),
				manageTableDO.getTargetTableName() + "数据同步开始...");
		// 执行开始时间
		Date beginTime = new Date();

		JdbcManager jdbcManager = new JdbcManager();
		DruidPooledConnection conn = null;
		// 同步结果集
		PreparedStatement ps = null;
		// 同步结果集
		ResultSet rs = null;
		// 同步数量
		long total = 0;
		try {
			List<ManageColumnsDO> listColumns = manageMetadataService.allManageColumns(manageTableDO.getTableId());
			if (null == listColumns || listColumns.size() == 0) {
				return 0l;
			}

			TechnicalTableDO technicalTableDO = technicalMetadataService.getById(manageTableDO.getSourceTableId());

			DataSourceDO dataSourceDO = (DataSourceDO) dataSourceService.getById(technicalTableDO.getTargetSourceId());

			// 源表查询字段
			StringBuffer selectColumns = new StringBuffer();

			// 目标表写入字段
			StringBuffer insertColumns = new StringBuffer();
			// 目标表写入动态匹配值(?)
			StringBuffer insertParams = new StringBuffer();
			String businessTime = null;
			// 迭代字段信息，构建查询字段，写入字段
			for (ManageColumnsDO manageColumnsDO : listColumns) {
				selectColumns.append(manageColumnsDO.getColumnName()).append(",");

				if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_INPUT_DATE + ",") >= 0) {
					businessTime = manageColumnsDO.getColumnName();
				}

				insertColumns.append(manageColumnsDO.getColumnName()).append(",");
				insertParams.append("?,");
			}

			StringBuffer fromSQL = new StringBuffer("select ");
			fromSQL.append(selectColumns.substring(0, selectColumns.length() - 1));
			fromSQL.append(" from ").append(manageTableDO.getSourceTableName());
			List<Object> queryParams = new ArrayList<Object>();
			if (Constant.CHANGE_TYPE_INCREMENT == manageTableDO.getChangeType()) {
				if (null == businessTime) {
					this.saveOperationLog(batchNo, jobId, manageTableDO.getTableId(), Constant.STATUS_DELETE, 0,
							"增量同步未配置入库时间字段，同步终止", beginTime, new Date());
					return 0l;
				}
				fromSQL.append(" where ");
				if (Constant.SOURCE_TYPE_ORACLE == dataSourceDO.getSourceType()) {
					fromSQL.append(" to_char(").append(businessTime).append(",'yyyymmdd') = ?");
				} else if (Constant.SOURCE_TYPE_MYSQL == dataSourceDO.getSourceType()) {
					fromSQL.append(" date_format(").append(businessTime).append(",'%Y%m%d') = ?");
				} else {
					this.saveOperationLog(batchNo, jobId, manageTableDO.getTableId(), Constant.STATUS_DELETE, 0,
							"未知数据库类型，同步终止", beginTime, new Date());

					return 0l;
				}
				queryParams.add(DateUtils.getYesterday("yyyyMMdd"));
			}

			DataSourceDO targetDataSourceDO = (DataSourceDO) dataSourceService
					.getById(manageTableDO.getTargetSourceId());
			// 字段标记信息
			Map<String, Object> tagMap = this.getTagInfo(listColumns);
			conn = this.getDBConnection(dataSourceDO.getSourceCode());
			// 查询需要交换的数据
			Map<String, Object> result = jdbcManager.executeQueryByType(conn, fromSQL.toString(),
					queryParams.toArray());
			rs = (ResultSet) result.get("rs");
			ps = (PreparedStatement) result.get("ps");

			if (Constant.CHANGE_TYPE_ALL == manageTableDO.getChangeType()) {
				String bakTableName = bakTable(manageTableDO.getTargetTableName(), targetDataSourceDO.getSourceCode());

				this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
						manageTableDO.getTargetTableName() + ",全量同步表备份为：" + bakTableName);
			}

			total = insertData2(batchNo, targetDataSourceDO.getSourceCode(), manageTableDO, listColumns,
					insertColumns.toString(), insertParams.toString(), rs, tagMap);
			try {
				if (null != ps) {
					ps.close();
				}
				if (null != conn) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

			this.saveOperationLog(batchNo, jobId, manageTableDO.getTableId(), Constant.STATUS_NORMAL, total, "成功",
					beginTime, new Date());

			// 历史未比对成功数据，重新比对
			total = this.updateHisData(batchNo, targetDataSourceDO.getSourceCode(), manageTableDO, listColumns, tagMap);
			this.saveOperationLog(batchNo, jobId, manageTableDO.getTableId(), Constant.STATUS_NORMAL, total, "历史数据比对成功",
					beginTime, new Date());

		} catch (Exception e) {
			e.printStackTrace();
			StringBuffer errorMsg = new StringBuffer(e.toString());
			errorMsg.append("\n");
			StackTraceElement[] ses = e.getStackTrace();
			errorMsg.append(ses[ses.length - 1]);

			this.saveOperationLog(batchNo, jobId, manageTableDO.getTableId(), Constant.STATUS_DELETE, total,
					errorMsg.toString(), beginTime, new Date());
		} finally {

			try {
				if (null != ps) {
					ps.close();
				}
				if (null != conn) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
				manageTableDO.getTargetTableName() + "数据同步结束...");

		return total;
	}

	/**
	 * 写入数据
	 * 
	 * @param jdbcManager      执行SQL管理类
	 * @param insertConn       写入数据源连接
	 * @param technicalTableDO 技术元数据表DO
	 * @param listColumns      技术元数据表列集合
	 * @param insertColumns    需要插入的表字段
	 * @param insertParams     需要插入的动态匹配参数
	 * @param rs               归集结果集
	 * @param tagMap           字段标记信息
	 * @return
	 * @throws Exception
	 */
	public long insertData2(Long batchNo, String dataSourceCode, ManageTableDO manageTableDO,
			List<ManageColumnsDO> listColumns, String insertColumns, String insertParams, ResultSet rs,
			Map<String, Object> tagMap) throws Exception {

		String insertSQL = this.buildInsertManageSQL(batchNo, manageTableDO, insertColumns, insertParams);

		CodeDO legalCodeDO = codeService.getByName(Constant.KEY_LEGAL_PERSON_TABLES);
		// 法人辨识来源表
		List<String> baseLegalTableList = new ArrayList<String>();
		if (null != legalCodeDO && !StringUtils.isEmpty(legalCodeDO.getCodeValue())) {
			String[] tableNames = legalCodeDO.getCodeValue().split(",");
			for (String tableName : tableNames) {
				baseLegalTableList.add(tableName.toLowerCase());
			}
		}
		CodeDO naturalCodeDO = codeService.getByName(Constant.KEY_NATURAL_PERSON_TABLES);
		// 自然人辨识来源表
		List<String> baseNaturalTableList = new ArrayList<String>();
		if (null != naturalCodeDO && !StringUtils.isEmpty(naturalCodeDO.getCodeValue())) {
			String[] tableNames = naturalCodeDO.getCodeValue().split(",");
			for (String tableName : tableNames) {
				baseNaturalTableList.add(tableName.toLowerCase());
			}
		}

		// 插入值
		List<Object> params = null;
		// 记录数
		long count = 0;
		// 去重字段值
		StringBuffer repeatMark = null;

		// 标记字段值
		Map<String, String> tagValueMap = null;

		String repeatSQL = "select * from " + manageTableDO.getTargetTableName() + " where repeat_mark = ?";

		// 待提交新增法人基础表数据
		List<BaseLegalPersonVO> addLegalList = new ArrayList<BaseLegalPersonVO>();

		// 待提交更新法人基础表数据
		List<BaseLegalPersonVO> updateLegalList = new ArrayList<BaseLegalPersonVO>();

		// 待提交新增法人基础表数据
		List<BaseNaturalPersonVO> addNaturalList = new ArrayList<BaseNaturalPersonVO>();

		// 扩展日志
		List<OperationExtLogVO> extLogVOList = new ArrayList<OperationExtLogVO>();
		// 管理元数据表批量提交数据
		List<Object[]> insertParamValues = new ArrayList<>();

		JdbcManager jdbcManager = new JdbcManager();
		while (rs.next()) {
			repeatMark = new StringBuffer();// 重置去重字段信息
			params = new ArrayList<Object>();// 重置写入参数数据

			// 法人基础辨识表数据批量写入
			if (addLegalList.size() >= COMMIT_SIZE_FOREACH) {
				this.baseLegalPersonService.batchSave(addLegalList);
				addLegalList = new ArrayList<BaseLegalPersonVO>();
			}
			// 法人基础辨识表数据批量更新
			if (updateLegalList.size() >= COMMIT_SIZE_FOREACH) {
				this.baseLegalPersonService.batchUpdate(addLegalList);
				updateLegalList = new ArrayList<BaseLegalPersonVO>();
			}
			// 自然人基础辨识表数据批量写入
			if (addNaturalList.size() >= COMMIT_SIZE_FOREACH) {
				this.baseNaturalPersonService.batchSave(addNaturalList);
				addNaturalList = new ArrayList<BaseNaturalPersonVO>();
			}
			// 操作元扩展日志批量写入
			if (extLogVOList.size() >= COMMIT_SIZE) {
				this.operationExtLogService.batchSave(extLogVOList);
				extLogVOList = new ArrayList<OperationExtLogVO>();
			}
			// 管理元数据批量写入
			if (insertParamValues.size() >= COMMIT_SIZE) {
				jdbcManager.batchExecuteSQL(this.getDBConnection(dataSourceCode), insertSQL, insertParamValues);
				insertParamValues = new ArrayList<Object[]>();
			}

			tagValueMap = this.getTagValue(rs, tagMap);
			String legalPersonId = null;// 法人唯一标识，法人基本辨识表归集时使用
			String naturalPersonId = null;// 自然人唯一标识，自然人基本辨识表归集时使用
			// 更新辨识表
			if (baseLegalTableList.contains(manageTableDO.getTargetTableName().toLowerCase())) {
				// 法人辨识数据来源表，更新法人辨识表
				legalPersonId = this.updateBaseLegalPerson(addLegalList, updateLegalList,
						tagValueMap.get("legalPersonName"), tagValueMap.get("uscc"), manageTableDO.getTableId(),
						batchNo);
			} else if (baseNaturalTableList.contains(manageTableDO.getTargetTableName().toLowerCase())) {
				// 自然人辨识数据来源表，更新自然人辨识表
				naturalPersonId = this.updateBaseNaturalPerson(addNaturalList, tagValueMap.get("naturalPersonName"),
						tagValueMap.get("idCard"), manageTableDO.getTableId(), batchNo);
			}

			List<String> repeatColumns = (ArrayList<String>) tagMap.get("repeatList");
			for (String str : repeatColumns) {
				repeatMark.append(null == rs.getObject(str) ? "" : rs.getObject(str).toString().trim());
			}

			// 去重信息不为空，进入去重逻辑
			if (!StringUtils.isEmpty(repeatMark)) {
				List<Map<String, Object>> list = jdbcManager.executeQuery(this.getDBConnection(dataSourceCode),
						repeatSQL, new Object[] { MD5Utils.MD5Encode(repeatMark.toString()) });
				boolean continueFlag = false;
				if (null != list && list.size() > 0) {
					Date oldDate = null;
					Date newDate = null;
					for (Map<String, Object> info : list) {
						boolean errorDate = false;
						try {
							newDate = (Date) info.get((String) tagMap.get("inputDate"));
							oldDate = (Date) rs.getObject((String) tagMap.get("inputDate"));
						} catch (Exception e) {
							errorDate = true;
						}
						if (!errorDate && !StringUtils.isEmpty((String) tagMap.get("inputDate"))) {
							if (DateUtils.differentMillisecond(newDate, oldDate) > 0) {
								// 当前数据入库时间迟于已入库数据时间，删除原来数据
								jdbcManager.executeSQL(this.getDBConnection(dataSourceCode),
										"delete from " + manageTableDO.getTargetTableName() + " where auto_id = ?",
										new Object[] { info.get("auto_id") });
								extLogVOList.add(new OperationExtLogVO(batchNo, Constant.META_TYPE_MANAGE,
										manageTableDO.getTableId(), "删除重复数据：" + JSONObject.toJSONString(info),
										new Date()));
							} else {
								extLogVOList.add(new OperationExtLogVO(batchNo, Constant.META_TYPE_MANAGE,
										manageTableDO.getTableId(),
										"存在重复数据：auto_id=" + info.get("auto_id") + "，新数据：" + this.getRsObject(rs),
										new Date()));

								continueFlag = true;
							}
						} else {
							// 没有入库时间字段，则直接删除原来数据，保存新数据
							jdbcManager.executeSQL(this.getDBConnection(dataSourceCode),
									"delete from " + manageTableDO.getTargetTableName() + " where auto_id = ?",
									new Object[] { info.get("auto_id") });
							extLogVOList.add(new OperationExtLogVO(batchNo, Constant.META_TYPE_MANAGE,
									manageTableDO.getTableId(), "删除重复数据：" + JSONObject.toJSONString(info), new Date()));
						}
					}
				}

				if (continueFlag) {
					continue;
				}
			}

			for (ManageColumnsDO manageColumnsDO : listColumns) {
				if (StringUtils.isEmpty(manageColumnsDO.getColumnName())) {
					params.add(null);
				} else {
					if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_INPUT_SECRET + ",") >= 0
							|| manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_ID_CARD + ",") >= 0
							|| manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_ID_CARD1 + ",") >= 0) {
						// 加密存储字段
						params.add(AESUtils.AESEncode(Constant.SECRET_KEY,
								(String) rs.getObject(manageColumnsDO.getColumnName())));
					} else {
						params.add(rs.getObject(manageColumnsDO.getColumnName()));
					}

				}

			}

			// 数据比对
			Object[] paramObjs = this.buildManageSpecialParams(legalPersonId, naturalPersonId, addLegalList,
					updateLegalList, addNaturalList, manageTableDO, tagValueMap, params, batchNo,
					repeatMark.toString());
			insertParamValues.add(paramObjs);
			count++;
			params = null;
		}

		// 法人基础辨识表数据批量写入
		if (addLegalList.size() > 0) {
			this.baseLegalPersonService.batchSave(addLegalList);
			addLegalList = new ArrayList<BaseLegalPersonVO>();
		}
		// 法人基础辨识表数据批量更新
		if (updateLegalList.size() > 0) {
			this.baseLegalPersonService.batchUpdate(addLegalList);
			updateLegalList = new ArrayList<BaseLegalPersonVO>();
		}
		// 自然人基础辨识表数据批量写入
		if (addNaturalList.size() > 0) {
			this.baseNaturalPersonService.batchSave(addNaturalList);
			addNaturalList = new ArrayList<BaseNaturalPersonVO>();
		}
		// 操作元扩展日志批量写入
		if (extLogVOList.size() > 0) {
			this.operationExtLogService.batchSave(extLogVOList);
			extLogVOList = new ArrayList<OperationExtLogVO>();
		}
		// 管理元数据批量写入
		if (insertParamValues.size() >= 0) {
			jdbcManager.batchExecuteSQL(this.getDBConnection(dataSourceCode), insertSQL, insertParamValues);
			insertParamValues = new ArrayList<Object[]>();
		}

		return count;
	}

	/**
	 * 构建管理元数据插入SQL
	 * 
	 * @param batchNo
	 * @param manageTableDO
	 * @param insertColumns
	 * @param insertParams
	 * @return
	 */
	private String buildInsertManageSQL(Long batchNo, ManageTableDO manageTableDO, String insertColumns,
			String insertParams) {
		StringBuffer insertSQL = new StringBuffer();
		insertSQL.append("insert into ").append(manageTableDO.getTargetTableName());
		insertSQL.append(" (").append(insertColumns);
		switch (manageTableDO.getDataType().intValue()) {
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON:
			insertSQL.append("LEGAL_PERSON_ID").append(",");
			insertParams += "?,";
			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON:
			insertSQL.append("NATURAL_PERSON_ID").append(",");
			insertParams += "?,";
			break;
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON:
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON:
			insertSQL.append("LEGAL_PERSON_ID,NATURAL_PERSON_ID").append(",");
			insertParams += "?,?,";
			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON:
			insertSQL.append("NATURAL_PERSON_ID，NATURAL_PERSON_ID1").append(",");
			insertParams += "?,?,";
			break;
		default:
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
					manageTableDO.getTargetTableName() + "存在未知数据类型");
			break;
		}

		insertSQL.append("REPEAT_MARK").append(")");
		insertParams += "?";
		insertSQL.append(" values (").append(insertParams).append(")");

		return insertSQL.toString();
	}

	/**
	 * 获取字段标记信息
	 * 
	 * @param listColumns
	 * @return
	 */
	private Map<String, Object> getTagInfo(List<ManageColumnsDO> listColumns) {
		Map<String, Object> tagMap = new HashMap<String, Object>();
		// 去重字段
		List<String> repeatList = new ArrayList<String>();

		for (ManageColumnsDO manageColumnsDO : listColumns) {

			// 提取标记信息
			if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_LEGAL_PERSON + ",") >= 0) {
				// 法人名称
				tagMap.put("legalPersonName", manageColumnsDO.getColumnName().toLowerCase());
			} else if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_USCC + ",") >= 0) {
				// 统一社会信用代码
				tagMap.put("uscc", manageColumnsDO.getColumnName().toLowerCase());
			} else if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_NATURAL_PERSON + ",") >= 0) {
				// 自然人姓名
				tagMap.put("naturalPersonName", manageColumnsDO.getColumnName().toLowerCase());
			} else if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_ID_CARD + ",") >= 0) {
				// 自然人身份证号码
				tagMap.put("idCard", manageColumnsDO.getColumnName().toLowerCase());
			} else if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_NATURAL_PERSON1 + ",") >= 0) {
				// 第二个自然人姓名
				tagMap.put("naturalPersonName1", manageColumnsDO.getColumnName().toLowerCase());
			} else if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_ID_CARD1 + ",") >= 0) {
				// 第二个自然人身份证号码
				tagMap.put("idCard1", manageColumnsDO.getColumnName().toLowerCase());
			} else if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_INPUT_DATE + ",") >= 0) {
				// 入库时间
				tagMap.put("inputDate", manageColumnsDO.getColumnName().toLowerCase());
			}

			if (manageColumnsDO.getColumnTag().indexOf(Constant.COLUMN_TAG_TYPE_REPEAT_MARK + ",") >= 0) {
				// 去重字段
				repeatList.add(manageColumnsDO.getColumnName().toLowerCase());
			}

		}

		tagMap.put("repeatList", repeatList);

		return tagMap;
	}

	/**
	 * 获取标记字段值
	 * 
	 * @param listColumns
	 * @return
	 */
	private Map<String, String> getTagValue(ResultSet rs, Map<String, Object> tagMap) throws Exception {
		Map<String, String> tagValueMap = new HashMap<String, String>();

		if (!StringUtils.isEmpty((String) tagMap.get("legalPersonName"))) {
			// 法人名称
			tagValueMap.put("legalPersonName",
					StringUtils.formatString((String) rs.getObject((String) tagMap.get("legalPersonName"))));
		}
		if (!StringUtils.isEmpty((String) tagMap.get("uscc"))) {
			// 统一社会信用代码
			tagValueMap.put("uscc", StringUtils.formatString((String) rs.getObject((String) tagMap.get("uscc"))));
		}
		if (!StringUtils.isEmpty((String) tagMap.get("naturalPersonName"))) {
			// 自然人姓名
			tagValueMap.put("naturalPersonName",
					StringUtils.formatString((String) rs.getObject((String) tagMap.get("naturalPersonName"))));
		}
		if (!StringUtils.isEmpty((String) tagMap.get("idCard"))) {
			// 身份证号码，加密存储
			String idCard = (String) rs.getObject((String) tagMap.get("idCard"));
			if (!StringUtils.isEmpty(idCard)) {
				tagValueMap.put("idCard",
						AESUtils.AESEncode(Constant.SECRET_KEY, StringUtils.formatString(idCard).toUpperCase()));
			} else {
				tagValueMap.put("idCard", null);
			}

		}
		if (!StringUtils.isEmpty((String) tagMap.get("naturalPersonName1"))) {
			// 自然人姓名1
			tagValueMap.put("naturalPersonName1",
					StringUtils.formatString((String) rs.getObject((String) tagMap.get("naturalPersonName1"))));

		}
		if (!StringUtils.isEmpty((String) tagMap.get("idCard1"))) {
			// 身份证号码1，加密存储
			tagValueMap.put("idCard1",
					AESUtils.AESEncode(Constant.SECRET_KEY,
							StringUtils.formatString((String) rs.getObject((String) tagMap.get("idCard1"))))
							.toUpperCase());
		}

		return tagValueMap;
	}

	/**
	 * 更新法人辨识表
	 * 
	 * @param baseLegalList   未提交辨识
	 * @param legalPersonName
	 * @param uscc
	 * @param tableId
	 * @param batchNo
	 */
	private String updateBaseLegalPerson(List<BaseLegalPersonVO> addLegalList, List<BaseLegalPersonVO> updateLegalList,
			String legalPersonName, String uscc, Long tableId, Long batchNo) {
		String legalPersonId = null;
		BaseLegalPersonVO baseLegalPersonVO = null;
		if (StringUtils.isEmpty(legalPersonName)) {
			return null;
		}
		try {
			baseLegalPersonVO = basePersonCache.getLegalPersonIdByUscc(uscc);

			if (null != baseLegalPersonVO && !StringUtils.isEmpty(baseLegalPersonVO.getLegalPersonId())) {
				legalPersonId = baseLegalPersonVO.getLegalPersonId();
				if (!legalPersonName.equals(baseLegalPersonVO.getLegalPersonName())) {
					baseLegalPersonVO = basePersonCache.getLegalPersonIdByLegalPersonName(legalPersonName);
					if (null == baseLegalPersonVO) {
						baseLegalPersonVO = basePersonCache.putLegalPerson(uscc, legalPersonName);
						addLegalList.add(baseLegalPersonVO);
					}
				}
				return legalPersonId;

			} else {
				baseLegalPersonVO = basePersonCache.getLegalPersonIdByLegalPersonName(legalPersonName);
				if (null == baseLegalPersonVO) {
					baseLegalPersonVO = basePersonCache.putLegalPerson(uscc, legalPersonName);
					if (null != baseLegalPersonVO) {
						legalPersonId = baseLegalPersonVO.getLegalPersonId();
						addLegalList.add(baseLegalPersonVO);
					}
				} else {
					legalPersonId = baseLegalPersonVO.getLegalPersonId();
					if (StringUtils.isEmpty(baseLegalPersonVO.getUscc())) {
						baseLegalPersonVO = basePersonCache.putLegalPerson(uscc, legalPersonName);
						updateLegalList.add(baseLegalPersonVO);
					}
				}
			}
		} catch (Exception e) {
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, tableId, "更新法人辨识表出错" + e.getMessage());
		}
		return legalPersonId;
	}

	/**
	 * 更新自然人辨识表
	 * 
	 * @param addNaturalList 待提交新增自然人基础辨识数据
	 * @param name
	 * @param idCard
	 * @param tableId
	 * @param batchNo
	 */
	private String updateBaseNaturalPerson(List<BaseNaturalPersonVO> addNaturalList, String name, String idCard,
			Long tableId, Long batchNo) {
		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(idCard)) {
			return null;
		}
		BaseNaturalPersonVO baseNaturalPersonVO = null;
		String naturalPersonId = null;
		try {
			naturalPersonId = basePersonCache.getNaturalPersonId(name, idCard);
			if (StringUtils.isEmpty(naturalPersonId)) {
				baseNaturalPersonVO = basePersonCache.putNaturalPerson(name, idCard);
				if (null != baseNaturalPersonVO) {
					addNaturalList.add(baseNaturalPersonVO);
				}
			}
		} catch (Exception e) {
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, tableId, "更新自然人辨识表出错" + e.getMessage());
		}

		return naturalPersonId;
	}

	/**
	 * 数据比对，构建特殊字段值
	 * 
	 * @param legalPersonId   法人唯一标识
	 * @param naturalPersonId 自然人唯一标识
	 * @param addLegalList    未提交新增法人基础辨识数据
	 * @param updateLegalList 未提交修改法人基础辨识数据
	 * @param addNaturalList  未提交新增自然人基础辨识数据
	 * @param manageTableDO
	 * @param tagValueMap
	 * @param params
	 */
	private Object[] buildManageSpecialParams(String legalPersonId, String naturalPersonId,
			List<BaseLegalPersonVO> addLegalList, List<BaseLegalPersonVO> updateLegalList,
			List<BaseNaturalPersonVO> addNaturalList, ManageTableDO manageTableDO, Map<String, String> tagValueMap,
			List<Object> params, Long batchNo, String repeatMark) throws Exception {
		List result = null;
		boolean isExists = false;
		switch (manageTableDO.getDataType().intValue()) {
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON:
			isExists = false;
			if (StringUtils.isEmpty(tagValueMap.get("legalPersonName"))) {
				// 法人名称为空，不进行比对
				params.add(null);
				isExists = true;
			}
			if (!isExists) {
				if (!StringUtils.isEmpty(legalPersonId)) {
					params.add(legalPersonId);
					isExists = true;
				}
			}

			if (!isExists) {
				// 用法人名称做比对。
				BaseLegalPersonVO vo = basePersonCache
						.getLegalPersonIdByLegalPersonName(tagValueMap.get("legalPersonName"));
				if (null != vo && !StringUtils.isEmpty(vo.getLegalPersonId())) {
					params.add(vo.getLegalPersonId());
				} else {
					params.add(null);
				}
			}

			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON:
			isExists = false;
			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
					|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
				// 自然人姓名为空或身份证号码为空，不进行比对
				params.add(null);
				isExists = true;
			}
			if (!isExists) {
				if (!StringUtils.isEmpty(naturalPersonId)) {
					params.add(naturalPersonId);
					isExists = true;
				}
			}

			if (!isExists) {
				// 用姓名与身份证做比对。
				naturalPersonId = basePersonCache.getNaturalPersonId(tagValueMap.get("naturalPersonName"),
						tagValueMap.get("idCard"));
				if (!StringUtils.isEmpty(naturalPersonId)) {
					params.add(naturalPersonId);
				} else {
					params.add(null);
				}
			}
			break;
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON:
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON:
			isExists = false;
			if (StringUtils.isEmpty(tagValueMap.get("legalPersonName"))) {
				// 法人名称为空，不进行比对
				params.add(null);
				isExists = true;
			}
			if (!isExists) {
				if (!StringUtils.isEmpty(legalPersonId)) {
					params.add(legalPersonId);
					isExists = true;
				}
			}

			if (!isExists) {
				// 用法人名称做比对。
				BaseLegalPersonVO vo = basePersonCache
						.getLegalPersonIdByLegalPersonName(tagValueMap.get("legalPersonName"));
				if (null != vo && !StringUtils.isEmpty(vo.getLegalPersonId())) {
					params.add(vo.getLegalPersonId());
				} else {
					params.add(null);
				}
			}

			isExists = false;
			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
					|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
				// 自然人姓名为空或身份证号码为空，不进行比对
				params.add(null);
				isExists = true;
			}
			if (!isExists) {
				if (!StringUtils.isEmpty(naturalPersonId)) {
					params.add(naturalPersonId);
					isExists = true;
				}
			}

			if (!isExists) {
				// 用姓名与身份证做比对。
				naturalPersonId = basePersonCache.getNaturalPersonId(tagValueMap.get("naturalPersonName"),
						tagValueMap.get("idCard"));
				if (!StringUtils.isEmpty(naturalPersonId)) {
					params.add(naturalPersonId);
				} else {
					params.add(null);
				}
			}
			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON:
			isExists = false;
			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
					|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
				// 自然人姓名为空或身份证号码为空，不进行比对
				params.add(null);
				isExists = true;
			}
			if (!isExists) {
				if (!StringUtils.isEmpty(naturalPersonId)) {
					params.add(naturalPersonId);
					isExists = true;
				}
			}

			if (!isExists) {
				// 用姓名与身份证做比对。
				naturalPersonId = basePersonCache.getNaturalPersonId(tagValueMap.get("naturalPersonName"),
						tagValueMap.get("idCard"));
				if (!StringUtils.isEmpty(naturalPersonId)) {
					params.add(naturalPersonId);
				} else {
					params.add(null);
				}
			}

			isExists = false;
			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName1"))
					|| StringUtils.isEmpty(tagValueMap.get("idCard1"))) {
				// 自然人姓名为空或身份证号码为空，不进行比对
				params.add(null);
				isExists = true;
			}

			if (!isExists) {
				// 用姓名与身份证做比对。
				naturalPersonId = basePersonCache.getNaturalPersonId(tagValueMap.get("naturalPersonName1"),
						tagValueMap.get("idCard1"));
				if (!StringUtils.isEmpty(naturalPersonId)) {
					params.add(naturalPersonId);
				} else {
					params.add(null);
				}
			}
			break;
		default:
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
					manageTableDO.getTargetTableName() + "存在未知数据类型");
			break;
		}
		params.add(MD5Utils.MD5Encode(repeatMark.toString()));

		result = null;

		return params.toArray();
	}

//	/**
//	 * 更新法人辨识表
//	 * 
//	 * @param baseLegalList   未提交辨识
//	 * @param legalPersonName
//	 * @param uscc
//	 * @param tableId
//	 * @param batchNo
//	 */
//	private String updateBaseLegalPerson(List<BaseLegalPersonVO> addLegalList, List<BaseLegalPersonVO> updateLegalList,
//			String legalPersonName, String uscc, Long tableId, Long batchNo) {
//		BaseLegalPersonVO baseLegalPersonVO = null;
//		if (StringUtils.isEmpty(legalPersonName)) {
//			return null;
//		}
//		try {
//			boolean isExists = false;
//			if (!StringUtils.isEmpty(uscc)) {
//				// 统一社会信用代码不为空，先在未提交数据中进行比对
//				for (BaseLegalPersonVO baseVo : addLegalList) {
//					if (uscc.equals(baseVo.getUscc())) {
//						if (legalPersonName.equals(baseVo.getLegalPersonName())) {
//							// 基础表中已存在，无需处理
//							return baseVo.getLegalPersonId();
//						} else {
//							// 统一社会信用代码匹配，但是法人名称不匹配，存在更名情况，增加基础数据
//							baseLegalPersonVO = new BaseLegalPersonVO();
//							baseLegalPersonVO.setLegalPersonId(baseVo.getLegalPersonId());// 沿用前面的法人唯一ID
//							baseLegalPersonVO.setLegalPersonName(legalPersonName);
//							baseLegalPersonVO.setUscc(uscc);
//							break;
//						}
//					}
//				}
//				if (null != baseLegalPersonVO) {
//					addLegalList.add(baseLegalPersonVO);
//					return baseLegalPersonVO.getLegalPersonId();
//				}
//
//				for (BaseLegalPersonVO baseVo : updateLegalList) {
//					if (uscc.equals(baseVo.getUscc())) {
//						if (legalPersonName.equals(baseVo.getLegalPersonName())) {
//							// 基础表中已存在，无需处理
//							return baseVo.getLegalPersonId();
//						} else {
//							// 统一社会信用代码匹配，但是法人名称不匹配，存在更名情况，增加基础数据
//							baseLegalPersonVO = new BaseLegalPersonVO();
//							baseLegalPersonVO.setLegalPersonId(baseVo.getLegalPersonId());// 沿用前面的法人唯一ID
//							baseLegalPersonVO.setLegalPersonName(legalPersonName);
//							baseLegalPersonVO.setUscc(uscc);
//							break;
//						}
//					}
//				}
//				if (null != baseLegalPersonVO) {
//					addLegalList.add(baseLegalPersonVO);
//					return baseLegalPersonVO.getLegalPersonId();
//				}
//
//				// 统一社会信用代码不为空，未提交数据中不存在，从数据库中进行比对
//				List<BaseLegalPersonDO> list = baseLegalPersonService.getLegalPerson(null, uscc);
//
//				if (null != list && list.size() > 0) {
//					String legalPersonId = null;
//					for (BaseLegalPersonDO baseLegalPersonDO : list) {
//						if (baseLegalPersonDO.getLegalPersonName().equals(legalPersonName)) {
//							isExists = true;
//							break;
//						}
//						legalPersonId = baseLegalPersonDO.getLegalPersonId();
//					}
//
//					if (!isExists && !StringUtils.isEmpty(legalPersonId)) {
//						// 统一社会信用代码存在记录但是法人名称不配置，写入新的辨识记录，沿用以前的唯一标识
//						baseLegalPersonVO = new BaseLegalPersonVO();
//						baseLegalPersonVO.setLegalPersonId(legalPersonId);
//						baseLegalPersonVO.setLegalPersonName(legalPersonName);
//						baseLegalPersonVO.setUscc(uscc);
//						addLegalList.add(baseLegalPersonVO);
//						return baseLegalPersonVO.getLegalPersonId();
//					}
//				} else {
//					// 统一社会信用代码不存在记录，根据名称去查
//					list = baseLegalPersonService.getLegalPerson(legalPersonName, null);
//
//					if (null == list || list.size() == 0) {
//						// 法人名称查询不存在直接写入
//						baseLegalPersonVO = new BaseLegalPersonVO();
//						baseLegalPersonVO.setLegalPersonId(MD5Utils.MD5Encode(legalPersonName));
//						baseLegalPersonVO.setLegalPersonName(legalPersonName);
//						baseLegalPersonVO.setUscc(uscc);
//						addLegalList.add(baseLegalPersonVO);
//						return baseLegalPersonVO.getLegalPersonId();
//					} else {
//						// 法人名称存在记录
//						for (BaseLegalPersonDO baseLegalPersonDO : list) {
//							if (null == baseLegalPersonDO.getUscc() || "".equals(baseLegalPersonDO.getUscc())) {
//								// 法人名称存在，统一社会信用代码为空，则更新统一社会信用代码
//								baseLegalPersonVO = new BaseLegalPersonVO();
//								baseLegalPersonVO.setAutoId(baseLegalPersonDO.getAutoId());
//								baseLegalPersonVO.setLegalPersonId(baseLegalPersonDO.getLegalPersonId());
//								baseLegalPersonVO.setLegalPersonName(legalPersonName);
//								baseLegalPersonVO.setUscc(uscc);
//								updateLegalList.add(baseLegalPersonVO);
//								return baseLegalPersonVO.getLegalPersonId();
//							}
//						}
//					}
//				}
//			} else {
//				// 统一社会信用代码不为空，先在未提交数据中进行比对
//				for (BaseLegalPersonVO baseVo : addLegalList) {
//					if (legalPersonName.equals(baseVo.getLegalPersonName())) {
//						if (legalPersonName.equals(baseVo.getLegalPersonName())) {
//							// 基础表中已存在，无需处理
//							return baseVo.getLegalPersonId();
//						} else {
//							// 统一社会信用代码匹配，但是法人名称不匹配，存在更名情况，增加基础数据
//							baseLegalPersonVO = new BaseLegalPersonVO();
//							baseLegalPersonVO.setLegalPersonId(baseVo.getLegalPersonId());// 沿用前面的法人唯一ID
//							baseLegalPersonVO.setLegalPersonName(legalPersonName);
//							baseLegalPersonVO.setUscc(uscc);
//						}
//					}
//				}
//
//				if (null != baseLegalPersonVO) {
//					addLegalList.add(baseLegalPersonVO);
//					return baseLegalPersonVO.getLegalPersonId();
//				}
//
//				for (BaseLegalPersonVO baseVo : updateLegalList) {
//					if (legalPersonName.equals(baseVo.getLegalPersonName())) {
//						return baseVo.getLegalPersonId();
//					}
//				}
//
//				// 统一社会信用代码不为空，未提交数据中不存在，从数据库中进行比对
//				List<BaseLegalPersonDO> list = baseLegalPersonService.getLegalPerson(legalPersonName, null);
//
//				if (null == list || list.size() == 0) {
//					baseLegalPersonVO = new BaseLegalPersonVO();
//					baseLegalPersonVO.setLegalPersonId(MD5Utils.MD5Encode(legalPersonName));
//					baseLegalPersonVO.setLegalPersonName(legalPersonName);
//					baseLegalPersonVO.setUscc(uscc);
//					addLegalList.add(baseLegalPersonVO);
//					return baseLegalPersonVO.getLegalPersonId();
//				}
//			}
//		} catch (Exception e) {
//			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, tableId, "更新法人辨识表出错" + e.getMessage());
//		}
//		return null;
//	}
//
//	/**
//	 * 更新自然人辨识表
//	 * 
//	 * @param addNaturalList 待提交新增自然人基础辨识数据
//	 * @param name
//	 * @param idCard
//	 * @param tableId
//	 * @param batchNo
//	 */
//	private String updateBaseNaturalPerson(List<BaseNaturalPersonVO> addNaturalList, String name, String idCard,
//			Long tableId, Long batchNo) {
//		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(idCard)) {
//			return null;
//		}
//		BaseNaturalPersonVO baseNaturalPersonVO = null;
//		try {
//			for (BaseNaturalPersonVO baseVo : addNaturalList) {
//				if (name.equals(baseVo.getName()) && idCard.equals(baseVo.getIdCard())) {
//					// 姓名身份证在基础辨识数据中存在，不在加入
//					return baseVo.getNaturalPersonId();
//				}
//			}
//
//			// 通过姓名、身份证号码比对
//			List<BaseNaturalPersonDO> list = baseNaturalPersonService.getNaturalPerson(name, idCard);
//
//			if (null == list || list.size() == 0) {
//				// 身份证号码不存在记录，直接写入
//				baseNaturalPersonVO = new BaseNaturalPersonVO();
//				baseNaturalPersonVO
//						.setNaturalPersonId(MD5Utils.MD5Encode(AESUtils.AESDecode(Constant.SECRET_KEY, idCard)));
//				baseNaturalPersonVO.setName(name);
//				baseNaturalPersonVO.setIdCard(idCard);
//
//				addNaturalList.add(baseNaturalPersonVO);
//
//				return baseNaturalPersonVO.getNaturalPersonId();
//			}
//		} catch (Exception e) {
//			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, tableId, "更新自然人辨识表出错" + e.getMessage());
//		}
//
//		return null;
//	}
//
//	/**
//	 * 数据比对，构建特殊字段值
//	 * 
//	 * @param legalPersonId   法人唯一标识
//	 * @param naturalPersonId 自然人唯一标识
//	 * @param addLegalList    未提交新增法人基础辨识数据
//	 * @param updateLegalList 未提交修改法人基础辨识数据
//	 * @param addNaturalList  未提交新增自然人基础辨识数据
//	 * @param manageTableDO
//	 * @param tagValueMap
//	 * @param params
//	 */
//	private Object[] buildManageSpecialParams(String legalPersonId, String naturalPersonId,
//			List<BaseLegalPersonVO> addLegalList, List<BaseLegalPersonVO> updateLegalList,
//			List<BaseNaturalPersonVO> addNaturalList, ManageTableDO manageTableDO, Map<String, String> tagValueMap,
//			List<Object> params, Long batchNo, String repeatMark) throws Exception {
//		List result = null;
//		boolean isExists = false;
//		switch (manageTableDO.getDataType().intValue()) {
//		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON:
//			isExists = false;
//			if (StringUtils.isEmpty(tagValueMap.get("legalPersonName"))) {
//				// 法人名称为空，不进行比对
//				params.add(null);
//				isExists = true;
//			}
//			if (!isExists) {
//				if (!StringUtils.isEmpty(legalPersonId)) {
//					params.add(legalPersonId);
//					isExists = true;
//				}
//			}
//			if (!isExists) {
//				// 遍历未提交新增的基础辨识数据，法人基础辨识数据来源表会进入该流程
//				for (BaseLegalPersonVO baseLegalPersonVO : addLegalList) {
//					if (tagValueMap.get("legalPersonName").equals(baseLegalPersonVO.getLegalPersonName())) {
//						params.add(baseLegalPersonVO.getLegalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 遍历未提交修改的基础辨识数据，法人基础辨识数据来源表会进入该流程
//				for (BaseLegalPersonVO baseLegalPersonVO : updateLegalList) {
//					if (tagValueMap.get("legalPersonName").equals(baseLegalPersonVO.getLegalPersonName())) {
//						params.add(baseLegalPersonVO.getLegalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 用法人名称做比对。
//				result = baseLegalPersonService.getLegalPerson(tagValueMap.get("legalPersonName"), null);
//				if (null != result && result.size() > 0) {
//					BaseLegalPersonDO baseLegalPersonDO = (BaseLegalPersonDO) result.get(0);
//					params.add(baseLegalPersonDO.getLegalPersonId());
//				} else {
//					params.add(null);
//				}
//			}
//
//			break;
//		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON:
//			isExists = false;
//			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
//					|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
//				// 自然人姓名为空或身份证号码为空，不进行比对
//				params.add(null);
//				isExists = true;
//			}
//			if (!isExists) {
//				if (!StringUtils.isEmpty(naturalPersonId)) {
//					params.add(naturalPersonId);
//					isExists = true;
//				}
//			}
//			if (!isExists) {
//				// 遍历未提交新增的基础辨识数据，自然人基础辨识数据来源表会进入该流程
//				for (BaseNaturalPersonVO baseNaturalPersonVO : addNaturalList) {
//					if (tagValueMap.get("naturalPersonName").equals(baseNaturalPersonVO.getName())
//							&& tagValueMap.get("idCard").equals(baseNaturalPersonVO.getIdCard())) {
//						params.add(baseNaturalPersonVO.getNaturalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 用姓名与身份证做比对。
//				result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName"),
//						tagValueMap.get("idCard"));
//				if (null != result && result.size() > 0) {
//					BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
//					params.add(baseNaturalPersonDO.getNaturalPersonId());
//				} else {
//					params.add(null);
//				}
//			}
//			break;
//		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON:
//		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON:
//			isExists = false;
//			if (StringUtils.isEmpty(tagValueMap.get("legalPersonName"))) {
//				// 法人名称为空，不进行比对
//				params.add(null);
//				isExists = true;
//			}
//			if (!isExists) {
//				if (!StringUtils.isEmpty(legalPersonId)) {
//					params.add(legalPersonId);
//					isExists = true;
//				}
//			}
//			if (!isExists) {
//				// 遍历未提交新增的基础辨识数据，法人基础辨识数据来源表会进入该流程
//				for (BaseLegalPersonVO baseLegalPersonVO : addLegalList) {
//					if (tagValueMap.get("legalPersonName").equals(baseLegalPersonVO.getLegalPersonName())) {
//						params.add(baseLegalPersonVO.getLegalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 遍历未提交修改的基础辨识数据，法人基础辨识数据来源表会进入该流程
//				for (BaseLegalPersonVO baseLegalPersonVO : updateLegalList) {
//					if (tagValueMap.get("legalPersonName").equals(baseLegalPersonVO.getLegalPersonName())) {
//						params.add(baseLegalPersonVO.getLegalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 用法人名称做比对。
//				result = baseLegalPersonService.getLegalPerson(tagValueMap.get("legalPersonName"), null);
//				if (null != result && result.size() > 0) {
//					BaseLegalPersonDO baseLegalPersonDO = (BaseLegalPersonDO) result.get(0);
//					params.add(baseLegalPersonDO.getLegalPersonId());
//				} else {
//					params.add(null);
//				}
//			}
//
//			isExists = false;
//			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
//					|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
//				// 自然人姓名为空或身份证号码为空，不进行比对
//				params.add(null);
//				isExists = true;
//			}
//			if (!isExists) {
//				// 遍历未提交新增的基础辨识数据，自然人基础辨识数据来源表会进入该流程
//				for (BaseNaturalPersonVO baseNaturalPersonVO : addNaturalList) {
//					if (tagValueMap.get("naturalPersonName").equals(baseNaturalPersonVO.getName())
//							&& tagValueMap.get("idCard").equals(baseNaturalPersonVO.getIdCard())) {
//						params.add(baseNaturalPersonVO.getNaturalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 用姓名与身份证做比对。
//				result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName"),
//						tagValueMap.get("idCard"));
//				if (null != result && result.size() > 0) {
//					BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
//					params.add(baseNaturalPersonDO.getNaturalPersonId());
//				} else {
//					params.add(null);
//				}
//			}
//			break;
//		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON:
//			isExists = false;
//
//			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
//					|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
//				// 自然人姓名为空或身份证号码为空，不进行比对
//				params.add(null);
//				isExists = true;
//			}
//			if (!isExists) {
//				if (!StringUtils.isEmpty(naturalPersonId)) {
//					params.add(naturalPersonId);
//					isExists = true;
//				}
//			}
//			if (!isExists) {
//				// 遍历未提交新增的基础辨识数据，自然人基础辨识数据来源表会进入该流程
//				for (BaseNaturalPersonVO baseNaturalPersonVO : addNaturalList) {
//					if (tagValueMap.get("naturalPersonName").equals(baseNaturalPersonVO.getName())
//							&& tagValueMap.get("idCard").equals(baseNaturalPersonVO.getIdCard())) {
//						params.add(baseNaturalPersonVO.getNaturalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 用姓名与身份证做比对。
//				result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName"),
//						tagValueMap.get("idCard"));
//				if (null != result && result.size() > 0) {
//					BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
//					params.add(baseNaturalPersonDO.getNaturalPersonId());
//				} else {
//					params.add(null);
//				}
//			}
//
//			isExists = false;
//			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName1"))
//					|| StringUtils.isEmpty(tagValueMap.get("idCard1"))) {
//				// 自然人姓名为空或身份证号码为空，不进行比对
//				params.add(null);
//				isExists = true;
//			}
//			if (!isExists) {
//				// 遍历未提交新增的基础辨识数据，自然人基础辨识数据来源表会进入该流程
//				for (BaseNaturalPersonVO baseNaturalPersonVO : addNaturalList) {
//					if (tagValueMap.get("naturalPersonName1").equals(baseNaturalPersonVO.getName())
//							&& tagValueMap.get("idCard1").equals(baseNaturalPersonVO.getIdCard())) {
//						params.add(baseNaturalPersonVO.getNaturalPersonId());
//						isExists = true;
//						break;
//					}
//				}
//			}
//			if (!isExists) {
//				// 用姓名与身份证做比对。
//
//				result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName1"),
//						tagValueMap.get("idCard1"));
//				if (null != result && result.size() > 0) {
//					BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
//					params.add(baseNaturalPersonDO.getNaturalPersonId());
//				} else {
//					params.add(null);
//				}
//			}
//			break;
//		default:
//			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
//					manageTableDO.getTargetTableName() + "存在未知数据类型");
//			break;
//		}
//		params.add(MD5Utils.MD5Encode(repeatMark.toString()));
//
//		result = null;
//
//		return params.toArray();
//	}

	/**
	 * 结果集转换
	 * 
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	private String getRsObject(ResultSet rs) throws SQLException {

		ResultSetMetaData md = rs.getMetaData();
		int columnCount = md.getColumnCount();
		Map<String, Object> rowData = null;

		rowData = new HashMap<String, Object>();

		for (int i = 1; i <= columnCount; i++) {
			rowData.put(md.getColumnName(i).toLowerCase(), rs.getObject(i));
		}

		return JSONObject.toJSONString(rowData);
	}

	/**
	 * 更新历史未比对成功数据
	 * 
	 * @param jdbcManager      执行SQL管理类
	 * @param updateConn       目标数据源连接
	 * @param technicalTableDO 技术元数据表DO
	 * @param listColumns      技术元数据表列集合
	 * @param insertColumns    需要插入的表字段
	 * @param insertParams     需要插入的动态匹配参数
	 * @param rs
	 * @return
	 * @throws Exception
	 */
	public long updateHisData(Long batchNo, String dataSourceCode, ManageTableDO manageTableDO,
			List<ManageColumnsDO> listColumns, Map<String, Object> tagMap) throws Exception {

		DruidPooledConnection conn = null;
		DruidPooledPreparedStatement ps = null;
		ResultSet rs = null;

		// 记录数
		long count = 0;

		try {
			String updateSQL = this.buildUpdateManageSQL(batchNo, manageTableDO);
			String querySQL = this.buildHisQuerySQL(batchNo, manageTableDO, tagMap);
			if (null == querySQL) {
				// 查询SQL构建失败
				return 0;
			}

			JdbcManager jdbcManager = new JdbcManager();
			Map<String, Object> result = jdbcManager.executeQueryByType(this.getDBConnection(dataSourceCode),
					querySQL.toString(), null);
			rs = (ResultSet) result.get("rs");
			ps = (DruidPooledPreparedStatement) result.get("ps");

			// 插入值
			List<Object> params = null;

			// 标记字段值
			Map<String, String> tagValueMap = null;

			List<Object[]> listParamValues = new ArrayList<Object[]>();

			while (rs.next()) {

				tagValueMap = this.getManageTagValue(rs, tagMap);

				// 数据比对
				params = this.buildManageUpdateParams(rs, manageTableDO, tagValueMap, batchNo);

				boolean isExec = false;
				for (Object obj : params) {
					if (null != obj) {
						isExec = true;
						break;
					}
				}

				// 存在有效参数，执行更新
				if (isExec) {
					listParamValues.add(params.toArray());
					count++;
				}
				if (listParamValues.size() >= COMMIT_SIZE) {
					jdbcManager.batchExecuteSQL(this.getDBConnection(dataSourceCode), updateSQL, listParamValues);
				}

				params = null;
			}

			if (listParamValues.size() > 0) {
				jdbcManager.batchExecuteSQL(this.getDBConnection(dataSourceCode), updateSQL, listParamValues);
			}
		} catch (Exception e) {
			throw e;
		} finally {

			try {
				if (null != ps) {
					ps.close();
				}
				if (null != conn) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		return count;
	}

	/**
	 * 构建管理元数据历史需比对数据查询SQL
	 * 
	 * @param batchNo
	 * @param manageTableDO
	 * @return
	 */
	private String buildHisQuerySQL(Long batchNo, ManageTableDO manageTableDO, Map<String, Object> tagMap) {
		StringBuffer querySQL = new StringBuffer("select ");
		boolean existsTag = false;
		for (String key : tagMap.keySet()) {
			if (!"repeatList".equals(key) && !StringUtils.isEmpty((String) tagMap.get(key))) {
				querySQL.append((String) tagMap.get(key)).append(",");
				existsTag = true;
			}
		}
		if (!existsTag) {
			// 不存在标记信息直接终止
			return null;
		}

		String whereSQL = "";
		switch (manageTableDO.getDataType().intValue()) {
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON:
			querySQL.append("legal_person_id,");
			whereSQL = " where legal_person_id is null";
			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON:
			querySQL.append("natural_person_id,");
			whereSQL = " where natural_person_id is null";
			break;
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON:
			querySQL.append("natural_person_id,legal_person_id,");
			whereSQL = " where natural_person_id is null and legal_person_id is null";
			break;
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON:
			querySQL.append("natural_person_id,legal_person_id,");
			whereSQL = " where natural_person_id is null or legal_person_id is null";
			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON:
			querySQL.append(" natural_person_id,natural_person_id1,");
			whereSQL = " where natural_person_id is null or natural_person_id1 is null";
			break;
		default:
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
					manageTableDO.getTargetTableName() + "存在未知数据类型");
			break;
		}

		querySQL.append("auto_id from ").append(manageTableDO.getTargetTableName()).append(whereSQL);

		return querySQL.toString();
	}

	/**
	 * 构建管理元数据更新SQL
	 * 
	 * @param batchNo
	 * @param manageTableDO
	 * @return
	 */
	private String buildUpdateManageSQL(Long batchNo, ManageTableDO manageTableDO) {
		StringBuffer updateSQL = new StringBuffer();
		updateSQL.append("update ").append(manageTableDO.getTargetTableName()).append(" set ");
		switch (manageTableDO.getDataType().intValue()) {
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON:
			updateSQL.append("LEGAL_PERSON_ID = ?");
			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON:
			updateSQL.append("NATURAL_PERSON_ID = ?");
			break;
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON:
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON:
			updateSQL.append("LEGAL_PERSON_ID = ?,NATURAL_PERSON_ID = ?");
			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON:
			updateSQL.append("NATURAL_PERSON_ID = ?,NATURAL_PERSON_ID1 = ?").append(",");
			break;
		default:
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
					manageTableDO.getTargetTableName() + "存在未知数据类型");
			break;
		}

		return updateSQL.toString();
	}

	/**
	 * 获取标记字段值
	 * 
	 * @param listColumns
	 * @return
	 */
	private Map<String, String> getManageTagValue(ResultSet rs, Map<String, Object> tagMap) throws Exception {
		Map<String, String> tagValueMap = new HashMap<String, String>();

		if (!StringUtils.isEmpty((String) tagMap.get("legalPersonName"))) {
			// 法人名称
			tagValueMap.put("legalPersonName",
					StringUtils.formatString((String) rs.getObject((String) tagMap.get("legalPersonName"))));
		}
		if (!StringUtils.isEmpty((String) tagMap.get("uscc"))) {
			// 统一社会信用代码
			tagValueMap.put("uscc", StringUtils.formatString((String) rs.getObject((String) tagMap.get("uscc"))));
		}
		if (!StringUtils.isEmpty((String) tagMap.get("naturalPersonName"))) {
			// 自然人姓名
			tagValueMap.put("naturalPersonName",
					StringUtils.formatString((String) rs.getObject((String) tagMap.get("naturalPersonName"))));
		}
		if (!StringUtils.isEmpty((String) tagMap.get("idCard"))) {
			tagValueMap.put("idCard", (String) rs.getObject((String) tagMap.get("idCard")));

		}
		if (!StringUtils.isEmpty((String) tagMap.get("naturalPersonName1"))) {
			// 自然人姓名1
			tagValueMap.put("naturalPersonName1",
					StringUtils.formatString((String) rs.getObject((String) tagMap.get("naturalPersonName1"))));

		}
		if (!StringUtils.isEmpty((String) tagMap.get("idCard1"))) {
			// 身份证号码1，加密存储
			tagValueMap.put("idCard1", (String) rs.getObject((String) tagMap.get("idCard1")));
		}

		return tagValueMap;
	}

	/**
	 * 以前未比对成功数据，重新进行数据比对
	 * 
	 * @param rs
	 * @param manageTableDO
	 * @param tagValueMap
	 * @param batchNo
	 */
	private List<Object> buildManageUpdateParams(ResultSet rs, ManageTableDO manageTableDO,
			Map<String, String> tagValueMap, Long batchNo) throws Exception {
		List<Object> params = new ArrayList<Object>();
		List result = null;
		switch (manageTableDO.getDataType().intValue()) {
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON:
			if (StringUtils.isEmpty(tagValueMap.get("legalPersonName"))) {
				params.add(null);
			} else {
				// 用法人名称做比对。
				result = baseLegalPersonService.getLegalPerson(tagValueMap.get("legalPersonName"), null);
				if (null != result && result.size() > 0) {
					BaseLegalPersonDO baseLegalPersonDO = (BaseLegalPersonDO) result.get(0);
					params.add(baseLegalPersonDO.getLegalPersonId());
				} else {
					params.add(null);
				}
			}

			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON:
			if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
					|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
				params.add(null);
			} else {
				// 用姓名与身份证做比对。
				result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName"),
						tagValueMap.get("idCard"));
				if (null != result && result.size() > 0) {
					BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
					params.add(baseNaturalPersonDO.getNaturalPersonId());
				} else {
					params.add(null);
				}
			}
			break;
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON:
		case Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON:
			if (null == rs.getObject("legal_person_id")) {
				if (StringUtils.isEmpty(tagValueMap.get("legalPersonName"))) {
					params.add(null);
				} else {
					// 用法人名称做比对。
					result = baseLegalPersonService.getLegalPerson(tagValueMap.get("legalPersonName"), null);
					if (null != result && result.size() > 0) {
						BaseLegalPersonDO baseLegalPersonDO = (BaseLegalPersonDO) result.get(0);
						params.add(baseLegalPersonDO.getLegalPersonId());
					} else {
						params.add(null);
					}
				}
			}

			if (null == rs.getObject("natural_person_id")) {
				if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
						|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
					params.add(null);
				} else {
					// 用姓名与身份证做比对。
					result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName"),
							tagValueMap.get("idCard"));
					if (null != result && result.size() > 0) {
						BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
						params.add(baseNaturalPersonDO.getNaturalPersonId());
					} else {
						params.add(null);
					}
				}
			}

			break;
		case Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON:
			if (null == rs.getObject("natural_person_id")) {
				if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName"))
						|| StringUtils.isEmpty(tagValueMap.get("idCard"))) {
					params.add(null);
				} else {
					// 用姓名与身份证做比对。
					result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName"),
							tagValueMap.get("idCard"));
					if (null != result && result.size() > 0) {
						BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
						params.add(baseNaturalPersonDO.getNaturalPersonId());
					} else {
						params.add(null);
					}
				}
			}

			if (null == rs.getObject("natural_person_id1")) {
				if (StringUtils.isEmpty(tagValueMap.get("naturalPersonName1"))
						|| StringUtils.isEmpty(tagValueMap.get("idCard1"))) {
					params.add(null);
				} else {
					// 用姓名与身份证做比对。
					result = baseNaturalPersonService.getNaturalPerson(tagValueMap.get("naturalPersonName1"),
							tagValueMap.get("idCard1"));
					if (null != result && result.size() > 0) {
						BaseNaturalPersonDO baseNaturalPersonDO = (BaseNaturalPersonDO) result.get(0);
						params.add(baseNaturalPersonDO.getNaturalPersonId());
					} else {
						params.add(null);
					}
				}
			}
			break;
		default:
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, manageTableDO.getTargetSourceId(),
					manageTableDO.getTargetTableName() + "存在未知数据类型");
			break;
		}

		result = null;
		return params;
	}

	/**
	 * 保存操作元日志
	 * 
	 * @param batchNo   批次号
	 * @param jobId     作业ID
	 * @param tableId   表ID
	 * @param status    状态
	 * @param total     数量
	 * @param desc      描述
	 * @param beginTime 开始时间
	 * @param endTime   结束时间
	 * @throws Exception
	 */
	public void saveOperationLog(Long batchNo, Long jobId, Long tableId, int status, long total, String desc,
			Date beginTime, Date endTime) {
		OperationLogVO logVO = new OperationLogVO();
		logVO.setBatchNo(batchNo);
		logVO.setImportType(Constant.IMPORT_TYPE_EXCHANGE);
		logVO.setJobId(jobId);
		logVO.setTableId(tableId);
		logVO.setStatus(status);
		logVO.setTotal(total);
		logVO.setDesc(desc);
		logVO.setBeginTime(beginTime);
		logVO.setEndTime(endTime);

		try {
			operationLogService.save(logVO);
		} catch (Exception e) {
			logger.error("操作元日志写入失败", e);
		}
	}

	/**
	 * 保存操作元详情日志
	 * 
	 * @param batchNo
	 * @param metaType
	 * @param tableId
	 * @param desc
	 * @throws Exception
	 */
	public void saveOperationExtLog(Long batchNo, int metaType, Long tableId, String desc) {
		OperationExtLogVO logVO = new OperationExtLogVO(batchNo, metaType, tableId, desc, new Date());

		try {
			operationExtLogService.save(logVO);
		} catch (Exception e) {
			logger.error("操作元详情日志写入失败", e);
		}
	}

	/**
	 * 备份业务元数据结果表
	 * 
	 * @param batchNo
	 * @param businessDataDO
	 * @throws Exception
	 */
	public void bakResultTable(Long batchNo, int dataType) {
		// TODO 考虑oracle与MYSQL语法区别
		// 结果表JDBC连接
		JdbcManager insertJdbcManager = new JdbcManager();
		try {
			if (null == this.getBaseDBConnection()) {
				this.saveOperationExtLog(batchNo, Constant.META_TYPE_BUSINESS, 0l, "业务元数据更新出错，数据源信息有误");
				return;
			}

			String tableName = null;
			String bakTableName = null;
			String dropIndexSQL = null;
			String addIndexSQL = null;
			if (dataType == Constant.BUSINESS_DATA_TYPE_LEGAL_PERSON) {
				tableName = "result_legal_person";
				bakTableName = "result_legal_person" + DateUtils.getYesterday("MMdd");
				dropIndexSQL = "ALTER TABLE `result_legal_person` DROP INDEX `idx_result_legal_person_01`";
				addIndexSQL = "ALTER TABLE `result_legal_person` ADD INDEX "
						+ "`idx_result_legal_person_01` (`legal_person_id`)";
			} else if (dataType == Constant.BUSINESS_DATA_TYPE_NATURAL_PERSON) {
				tableName = "result_natural_person";
				bakTableName = "result_natural_person" + DateUtils.getYesterday("MMdd");
				dropIndexSQL = "ALTER TABLE `result_natural_person` DROP INDEX `idx_result_natural_person_01`";
				addIndexSQL = "ALTER TABLE `result_natural_person` ADD INDEX "
						+ "`idx_result_natural_person_01` (`natural_person_id`)";
			}

			if (null == bakTableName) {
				return;
			}

			// 删除索引
			insertJdbcManager.executeSQL(this.getBaseDBConnection(), dropIndexSQL, new Object[] {});

			// 更换表名
			insertJdbcManager.executeSQL(this.getBaseDBConnection(),
					"alter table " + tableName + " RENAME TO " + bakTableName, new Object[] {});

			// 创建表
			insertJdbcManager.executeSQL(this.getBaseDBConnection(),
					"create table " + tableName + " as select * from " + bakTableName + " where 1 = 2",
					new Object[] {});
			// 创建索引
			insertJdbcManager.executeSQL(this.getBaseDBConnection(), addIndexSQL, new Object[] {});
		} catch (Exception e) {
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_BUSINESS, 0l, "结果表备份失败");
		}

	}

	/**
	 * 固化法人业务元数据
	 * 
	 * @param batchNo
	 * @param businessDataDO
	 */
	public void fixingLegalBusiMetadata(Long batchNo, BusinessDataDO businessDataDO) {
		this.saveOperationExtLog(batchNo, Constant.META_TYPE_BUSINESS, businessDataDO.getTableId(),
				businessDataDO.getBusiId() + "固化begin...");

		JdbcManager jdbcManager = new JdbcManager();
		// 查询JDBC
		DruidPooledConnection queryConn = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		try {
			// 来源数据源
			DataSourceDO dataSourceDO = null;
			if (Constant.DEL_FLAG_NORMAL == businessDataDO.getDelFlag()) {
				if (Constant.BUSI_DATA_ALGORITHMTYPE_INTERFACE == businessDataDO.getAlgorithmType()) {
					return;
				}
				if (null == businessDataDO.getDataSource() || 0 == businessDataDO.getDataSource()) {
					// 数据源信息不存在
					ManageTableDO manageTableDO = manageMetadataService.getById(businessDataDO.getTableId());
					dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());

				} else {
					dataSourceDO = (DataSourceDO) dataSourceService.getById(businessDataDO.getDataSource());
				}

				// 是否需要解码
				boolean decode = false;
				if (businessDataDO.getAlgorithmType() == Constant.BUSI_DATA_ALGORITHMTYPE_SINGLE) {
					ColumnDTO columnDTO = manageMetadataService.getColumnById(businessDataDO.getColumnId());
					if (!StringUtils.isEmpty(columnDTO.getColumnTag())) {
						String[] tag = columnDTO.getColumnTag().split(",");
						List<String> tagList = Arrays.asList(tag);
						if (tagList.contains(Constant.COLUMN_TAG_TYPE_ID_CARD + "")
								|| tagList.contains(Constant.COLUMN_TAG_TYPE_ID_CARD1 + "")) {
							decode = true;
						}
					}
				}

				queryConn = this.getDBConnection(dataSourceDO.getSourceCode());
				Map<String, Object> result = jdbcManager.executeQueryByType(queryConn, businessDataDO.getBusiSql(),
						null);
				rs = (ResultSet) result.get("rs");
				ps = (PreparedStatement) result.get("ps");

				String insertSQL = "insert into result_legal_person(legal_person_id,busi_id,busi_value) value (?,?,?)";
				// 参数集合
				List<Object[]> listParams = new ArrayList<Object[]>();
				// 上一条法人ID，用于单项统计时去重
				String previousLegalPeronId = "";
				while (rs.next()) {
					if (businessDataDO.getAlgorithmType() == Constant.BUSI_DATA_ALGORITHMTYPE_SINGLE) {
						if (previousLegalPeronId.equals((String) rs.getObject(2))) {
							// 重复数据
							continue;
						}
						previousLegalPeronId = (String) rs.getObject(2);
						if (decode) {
							// 解码
							listParams.add(new Object[] { rs.getObject(2), businessDataDO.getBusiId(),
									StringUtils.decodeIdCard((String) rs.getObject(3)) });
						} else {
							listParams
									.add(new Object[] { rs.getObject(2), businessDataDO.getBusiId(), rs.getObject(3) });
						}
					} else {
						listParams.add(new Object[] { rs.getObject(1), businessDataDO.getBusiId(), rs.getObject(2) });
					}
					if (listParams.size() >= COMMIT_SIZE) {
						jdbcManager.batchExecuteSQL(this.getBaseDBConnection(), insertSQL, listParams);
						listParams = new ArrayList<Object[]>();
					}
				}
				if (listParams.size() > 0) {
					jdbcManager.batchExecuteSQL(this.getBaseDBConnection(), insertSQL, listParams);
					listParams = new ArrayList<Object[]>();
				}
			}
		} catch (Exception e) {
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_BUSINESS, businessDataDO.getTableId(),
					"业务元数据更新出错" + e.getMessage());
		} finally {

			try {
				if (null != ps) {
					ps.close();
				}
				if (null != queryConn) {
					queryConn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		this.saveOperationExtLog(batchNo, Constant.META_TYPE_BUSINESS, businessDataDO.getTableId(),
				businessDataDO.getBusiId() + "固化end...");
	}

	/**
	 * 固化自然人人业务元数据
	 * 
	 * @param batchNo
	 * @param businessDataDO
	 */
	public void fixingNaturalBusiMetadata(Long batchNo, BusinessDataDO businessDataDO) {
		this.saveOperationExtLog(batchNo, Constant.META_TYPE_BUSINESS, businessDataDO.getTableId(),
				businessDataDO.getBusiId() + "固化begin...");

		JdbcManager jdbcManager = new JdbcManager();
		// 查询JDBC
		DruidPooledConnection queryConn = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		try {
			// 来源数据源
			DataSourceDO dataSourceDO = null;
			if (Constant.DEL_FLAG_NORMAL == businessDataDO.getDelFlag()) {
				if (Constant.BUSI_DATA_ALGORITHMTYPE_INTERFACE == businessDataDO.getAlgorithmType()) {
					return;
				}
				if (null == businessDataDO.getDataSource() || 0 == businessDataDO.getDataSource()) {
					// 数据源信息不存在
					ManageTableDO manageTableDO = manageMetadataService.getById(businessDataDO.getTableId());
					dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());

				} else {
					dataSourceDO = (DataSourceDO) dataSourceService.getById(businessDataDO.getDataSource());
				}

				// 是否需要解码
				boolean decode = false;
				if (businessDataDO.getAlgorithmType() == Constant.BUSI_DATA_ALGORITHMTYPE_SINGLE) {
					ColumnDTO columnDTO = manageMetadataService.getColumnById(businessDataDO.getColumnId());
					if (!StringUtils.isEmpty(columnDTO.getColumnTag())) {
						String[] tag = columnDTO.getColumnTag().split(",");
						List<String> tagList = Arrays.asList(tag);
						if (tagList.contains(Constant.COLUMN_TAG_TYPE_ID_CARD + "")
								|| tagList.contains(Constant.COLUMN_TAG_TYPE_ID_CARD1 + "")) {
							decode = true;
						}
					}
				}

				// 初始化查询JDBC
				queryConn = this.getDBConnection(dataSourceDO.getSourceCode());

				Map<String, Object> result = jdbcManager.executeQueryByType(queryConn, businessDataDO.getBusiSql(),
						null);
				rs = (ResultSet) result.get("rs");
				ps = (PreparedStatement) result.get("ps");

				String insertSQL = "insert into result_natural_person(natural_person_id,busi_id,busi_value) value (?,?,?)";
				// 参数集合
				List<Object[]> listParams = new ArrayList<Object[]>();

				// 上一条自然人ID，用于单项统计时去重
				String previousNaturalPeronId = "";
				while (rs.next()) {

					if (businessDataDO.getAlgorithmType() == Constant.BUSI_DATA_ALGORITHMTYPE_SINGLE) {
						if (previousNaturalPeronId.equals((String) rs.getObject(2))) {
							// 重复数据
							continue;
						}
						previousNaturalPeronId = (String) rs.getObject(2);
						if (decode) {
							// 解码
							listParams.add(new Object[] { rs.getObject(2), businessDataDO.getBusiId(),
									StringUtils.decodeIdCard((String) rs.getObject(3)) });
						} else {
							listParams
									.add(new Object[] { rs.getObject(2), businessDataDO.getBusiId(), rs.getObject(3) });
						}
					} else {
						listParams.add(new Object[] { rs.getObject(1), businessDataDO.getBusiId(), rs.getObject(2) });
					}
					if (listParams.size() >= COMMIT_SIZE) {
						jdbcManager.batchExecuteSQL(this.getBaseDBConnection(), insertSQL, listParams);
						listParams = new ArrayList<Object[]>();
					}

				}
				if (listParams.size() > 0) {
					jdbcManager.batchExecuteSQL(this.getBaseDBConnection(), insertSQL, listParams);
					listParams = new ArrayList<Object[]>();
				}
			}
		} catch (Exception e) {
			this.saveOperationExtLog(batchNo, Constant.META_TYPE_MANAGE, 0l, "业务元数据更新出错" + e.getMessage());
		} finally {

			try {
				if (null != ps) {
					ps.close();
				}
				if (null != queryConn) {
					queryConn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		this.saveOperationExtLog(batchNo, Constant.META_TYPE_BUSINESS, businessDataDO.getTableId(),
				businessDataDO.getBusiId() + "固化end...");
	}

	/**
	 * 查询待查询的企查查企业
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public PageUtils getQichachBase(int page) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("targetTableName", "T_QCC");
		Query query = new Query(condition);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Long total = 0l;

		PageUtils tablePageUtils = technicalMetadataService.list(query);
		if (null != tablePageUtils && null != tablePageUtils.getRows() && tablePageUtils.getRows().size() > 0) {
			TechnicalTableDO technicalTableDO = (TechnicalTableDO) tablePageUtils.getRows().get(0);

			// 获取数据源信息
			DataSourceDO dataSourceDO = (DataSourceDO) dataSourceService.getById(technicalTableDO.getTargetSourceId());

			int offset = (page - 1) * 10;
			String sql = "select qymc from T_QCC order by qymc limit " + offset + ",10";

			JdbcManager jdbcManager = new JdbcManager();
			list = jdbcManager.executeQuery(this.getDBConnection(dataSourceDO.getSourceCode()), sql, null);

			String countSql = "select count(qymc) as ct from T_QCC";
			List<Map<String, Object>> countList = jdbcManager
					.executeQuery(this.getDBConnection(dataSourceDO.getSourceCode()), countSql, null);
			if (null != countList && countList.size() > 0) {
				Map<String, Object> map = countList.get(0);
				total = (Long) map.get("ct");
			}
		}

		return new PageUtils(list, total.intValue());
	}

	/**
	 * 保存企查查数据
	 * 
	 * @param dataSourceCode
	 * @param sql
	 * @param listParams
	 */
	public void saveQichachaData(String dataSourceCode, String sql, List<Object[]> listParams) throws Exception {
		JdbcManager jdbcManager = new JdbcManager();
		DruidPooledConnection conn = this.getDBConnection(dataSourceCode);

		jdbcManager.batchExecuteSQL(conn, sql, listParams);
	}

	@Deprecated
	public void fixingEarlyWarningMetadata(Long batchNo, EarlyWarningDO earlyWarningDO) throws Exception {
		// TODO Auto-generated method stub
		this.saveOperationExtLog(batchNo, Constant.META_TYPE_EARLYWARNING, earlyWarningDO.getWarnTableId(),
				"信用预警固化begin...");

		JdbcManager jdbcManager = new JdbcManager();

		ManageTableDO manageTableDO = manageMetadataService.getById(earlyWarningDO.getWarnTableId());
		DataSourceDO dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());

		// 获取对应预警的企业信息
		Object[] params = { earlyWarningDO.getWarnId() };
		List<Map<String, Object>> companyList = jdbcManager.executeQuery(
				this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE),
				"select id,company_name,legal_person_id,status from result_early_warning where warn_id = ?", params);
		// 遍历查询该企业是否存在于对应的预警表中

		// 参数集合
		List<Object[]> listParams = new ArrayList<Object[]>();
		String updateSQL = "update result_early_warning set status = 0 where id = ? and legal_person_id = ? and warn_id = ?";
		for (Map<String, Object> i : companyList) {
			List<Map<String, Object>> result = jdbcManager.executeQuery(
					this.getDBConnection(dataSourceDO.getSourceCode()),
					"select * from " + earlyWarningDO.getWarnTable() + " where legal_person_id = ?",
					new Object[] { (String) i.get("legal_person_id") });
			if (result.size() != 0) {
				// 如果存在则修改企业表中对应的企业状态
				listParams.add(new Object[] { (Integer) i.get("id"), (String) i.get("legal_person_id"),
						earlyWarningDO.getWarnId() });
			}

			if (listParams.size() >= COMMIT_SIZE) {
				jdbcManager.batchExecuteSQL(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE), updateSQL,
						listParams);
				listParams = new ArrayList<Object[]>();
			}
		}
		if (listParams.size() > 0) {
			jdbcManager.batchExecuteSQL(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE), updateSQL, listParams);
			listParams = new ArrayList<Object[]>();
		}

		this.saveOperationExtLog(batchNo, Constant.META_TYPE_EARLYWARNING, earlyWarningDO.getWarnTableId(),
				"信用预警固化end...");
	}

	public void fixingWarningsMetadata(Long batchNo, WarningsModelDO warningsModelDO) throws Exception {
		// TODO: 待优化
		this.saveOperationExtLog(batchNo, Constant.META_TYPE_EARLYWARNING, warningsModelDO.getWarnId(),
				"信用预警ID:" + warningsModelDO.getWarnId() + ",信用预警固化begin...");

		JdbcManager jdbcManager = new JdbcManager();

		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("warnId", warningsModelDO.getWarnId());
		Query query = new Query(temp);

		List<WarningsBusiDO> busiList = warningsService.listBusi(query);

		// 获取对应预警的企业信息
		Object[] params = { warningsModelDO.getWarnId() };
		List<Map<String, Object>> companyList = jdbcManager.executeQuery(
				this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE),
				"select id,company_name,legal_person_id,dept_id,warn_id from result_warning where warn_id = ?", params);
		// 遍历查询该企业是否存在于对应的预警表中

		// 参数集合
		List<Object[]> listParams = new ArrayList<Object[]>();
		String updateSQL = "update result_warning set status = 0 where id = ? and legal_person_id = ? and warn_id = ? and dept_id = ? ";
		for (Map<String, Object> i : companyList) {
			boolean flag = false;

			for (WarningsBusiDO busi : busiList) {
				List<Map<String, Object>> result = jdbcManager.executeQuery(
						this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE),
						"select legal_person_id, busi_id, busi_value from result_legal_person where legal_person_id = ? and busi_id = ? ",
						new Object[] { (String) i.get("legal_person_id"), busi.getBusiId() });
				// 表中不存在对应数据
				if (result.size() <= 0) {
					String update = "update result_warning set status = 0 where id = ? and legal_person_id = ? and warn_id = ? and dept_id = ? ";
					jdbcManager.executeQuery(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE), update,
							new Object[] { i.get("id"), i.get("legal_person_id"), warningsModelDO.getWarnId(),
									i.get("dept_id") });
					continue;
				}
				long value = Long.valueOf(String.valueOf(result.get(0).get("busi_value"))).longValue();

				long number = busi.getNumber();
				switch (busi.getComparator()) {
				case ">":
					if (value > number) {
						flag = true;
					}
					break;
				case ">=":
					if (value >= number) {
						flag = true;
					}
					break;
				case "=":
					if (value == number) {
						flag = true;
					}
					break;
				case "<":
					if (value < number) {
						flag = true;
					}
					break;
				case "<=":
					if (value <= number) {
						flag = true;
					}
					break;
				default:
					flag = false;
					break;
				}
			}

			if (flag) {
				// 如果存在则修改企业表中对应的企业状态
				listParams.add(new Object[] { i.get("id"), i.get("legal_person_id"), warningsModelDO.getWarnId(),
						i.get("dept_id") });
			}

			if (listParams.size() >= COMMIT_SIZE) {
				jdbcManager.batchExecuteSQL(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE), updateSQL,
						listParams);
				listParams = new ArrayList<Object[]>();
			}
		}
		if (listParams.size() > 0) {
			jdbcManager.batchExecuteSQL(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE), updateSQL, listParams);
			listParams = new ArrayList<Object[]>();
		}

		this.saveOperationExtLog(batchNo, Constant.META_TYPE_EARLYWARNING, warningsModelDO.getWarnId(),
				"信用预警ID:" + warningsModelDO.getWarnId() + ",信用预警固化end...");
	}

}
